package com.zlc.workflow.aop;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zlc.common.annotation.SyncResourceConstant;
import com.zlc.common.core.process.model.entity.StoneCodeInterface;
import com.zlc.common.core.process.model.vo.StoneCodeInterfaceVo;
import com.zlc.common.core.process.service.StoneCodeInterfaceService;
import com.zlc.common.util.SpringContextUtils;
import com.zlc.workflow.anno.WorkflowCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

@Component
public class WorkflowCallbackInit {

    @Autowired
    private StoneCodeInterfaceService stoneCodeInterfaceService;

    @PostConstruct
    public void init() {
        List<StoneCodeInterfaceVo> stoneCodeInterfaceVos = stoneCodeInterfaceService.queryVoList(new LambdaQueryWrapper<>());
        ApplicationContext context = SpringContextUtils.getApplicationContext();

        Map<String, Object> resourceBeans = context.getBeansWithAnnotation(WorkflowCallback.class);
        for (Object resourceBean : resourceBeans.values()) {
            WorkflowCallback syncAnn = resourceBean.getClass().getAnnotation(WorkflowCallback.class);
            String className = resourceBean.getClass().getName();
            String description = syncAnn.description();
            String value = syncAnn.value();
            String module = syncAnn.module();

            StoneCodeInterfaceVo stoneCodeInterfaceVo = stoneCodeInterfaceVos.stream()
                    .filter(interfaceVo -> interfaceVo.getClassName().equals(className)).findFirst().orElse(null);
            if(!ObjectUtils.isEmpty(stoneCodeInterfaceVo)){
                if(!stoneCodeInterfaceVo.getDescription().equals(description) || !stoneCodeInterfaceVo.getValue().equals(value) ||
                               !stoneCodeInterfaceVo.getModule().equals(module)){
                    stoneCodeInterfaceVo.setDescription( description);
                    stoneCodeInterfaceVo.setValue(value);
                    stoneCodeInterfaceVo.setModule(module);
                    stoneCodeInterfaceService.saveVo(stoneCodeInterfaceVo);
                }
            }else{
                stoneCodeInterfaceVo = new StoneCodeInterfaceVo();
                stoneCodeInterfaceVo.setClassName(className);
                stoneCodeInterfaceVo.setDescription( description);
                stoneCodeInterfaceVo.setValue(value);
                stoneCodeInterfaceVo.setModule(module);
                stoneCodeInterfaceService.saveVo(stoneCodeInterfaceVo);
            }
        }
    }

}
